package net.daum.webtoon.android.io;

import net.daum.webtoon.android.util.Logger;

import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;

public class DaumWebToonsInitTask extends
		AsyncTask<JSONObject, Void, JSONObject> {

	private static final String TAG = DaumWebToonsInitTask.class
			.getSimpleName();
	private RESTFulClient restFulClient;
	private Runnable[] runnable;
	private int size;
	private int page;
	private Context context;

	public DaumWebToonsInitTask(Runnable... onPostRunnable) {
		this(null, 30, onPostRunnable);
	}

	public DaumWebToonsInitTask(int size, Runnable... onPostRunnable) {
		this(null, size, onPostRunnable);
	}

	public DaumWebToonsInitTask(Context context, int size,
			Runnable... onPostRunnable) {
		this(null, 1, size, onPostRunnable);
	}

	public DaumWebToonsInitTask(Context context, int page, int size,
			Runnable... onPostRunnable) {
		restFulClient = new RESTFulClient(context);
		this.runnable = onPostRunnable;
		this.size = size;
		this.page = page;
		this.context = context;
	}

	@Override
	protected JSONObject doInBackground(JSONObject... params) {
		JSONObject jsonObject = params[0];
		try {
			jsonObject = restFulClient.getDaumWebToon(page, size);
		} catch (Exception e) {
			Logger.e(TAG, e.getMessage(), e);
		}
		if (jsonObject != null) {
			Logger.i(TAG, jsonObject.toString());
		}
		return jsonObject;
	}

	@Override
	protected void onPostExecute(JSONObject result) {
		super.onPostExecute(result);
		if (runnable != null && result != null) {
			for (Runnable run : runnable) {
				new Handler().post(run);
			}
		} else {
			Logger.w(TAG, "result:" + result);
		}
	}

}